package com.actionsoft.bpms.server.fs.impl;

import com.actionsoft.bpms.bo.design.cache.BOCache;
import com.actionsoft.bpms.bo.design.model.BOModel;
import com.actionsoft.bpms.bpmn.engine.cache.ProcessDefCache;
import com.actionsoft.bpms.bpmn.engine.dao.ProcessRuntimeDaoFactory;
import com.actionsoft.bpms.bpmn.engine.model.def.ProcessDefinition;
import com.actionsoft.bpms.bpmn.engine.model.run.delegate.ProcessInstance;
import com.actionsoft.bpms.commons.formfile.FormFileUtil;
import com.actionsoft.bpms.commons.formfile.dao.FormFileDao;
import com.actionsoft.bpms.commons.formfile.model.FormFileModel;
import com.actionsoft.bpms.commons.formfile.model.delegate.FormFile;
import com.actionsoft.bpms.commons.security.high.HighSecurity;
import com.actionsoft.bpms.form.engine.FormEngineHelper;
import com.actionsoft.bpms.server.fs.AbstFileProcessor;
import com.actionsoft.bpms.server.fs.DCContext;
import com.actionsoft.bpms.server.fs.FileProcessorListener;
import com.actionsoft.bpms.server.fs.dc.DCProfileManager;
import com.actionsoft.bpms.server.fs.dc.DCStoreUtil;
import com.actionsoft.bpms.util.UUIDGener;
import com.actionsoft.bpms.util.UtilString;
import com.actionsoft.sdk.local.SDK;
import com.alibaba.fastjson.JSONObject;

import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URLDecoder;
import java.nio.charset.StandardCharsets;
import java.sql.Timestamp;
import java.util.Date;
import java.util.Map;

/**
 * 表单附件UI组件的文件库操作处理
 *
 * @author jack
 */
public class FormUIFileProcessor extends AbstFileProcessor implements FileProcessorListener {
    public boolean uploadReady(Map<String, Object> param) throws Exception {
        DCContext context = (DCContext)param.get("DCContext");
        if (context.getRepositoryName().equals("!form-ui-file-")) {
            String appId = context.getAppId();

            InputStream in = (InputStream)param.get("data");
            String configStr = context.getGroupValue();
            if ("wpsOA".equals(context.getExtParam())) {
                try {
                    configStr = URLDecoder.decode(configStr, StandardCharsets.UTF_8.name());
                } catch (Exception var21) {
                    var21.printStackTrace();
                }
            }

            JSONObject config = null;
            if (configStr.contains("{")) {
                config = UtilString.isEmpty(configStr) ? new JSONObject() : JSONObject.parseObject(configStr);
            }

            String processInstId = config == null ? "" : config.getString("processInstId");
            String taskInstId = config == null ? "" : config.getString("taskInstId");
            String boId = config == null ? "" : config.getString("boId");
            String formFileId = config == null ? "" : config.getString("formFileId");
            String boDefId = config == null ? "" : config.getString("boDefId");
            String boItemName = config == null ? "" : config.getString("boItemName");
            String remark = config == null ? "" : config.getString("remark");
            boolean isWPSOA = config == null ? false : config.containsKey("isWPSOA") && config.getBooleanValue("isWPSOA");
            Boolean copyOnly = config == null ? Boolean.FALSE : config.getBoolean("matrixCopyOnly");
            boolean copyFileOnly = copyOnly == null ? false : copyOnly;
            BOModel boModel = (BOModel)BOCache.getInstance().getModel(boDefId);
            boolean isCreate = false;
            if (isWPSOA) {
                FormFileDao dao = new FormFileDao();
                if (UtilString.isEmpty(formFileId)) {
                    isCreate = true;
                    formFileId = UUIDGener.getUUID();
                } else {
                    FormFile formFile = (FormFile)dao.queryById(formFileId);
                    if (formFile == null) {
                        isCreate = true;
                    }
                }
            } else if (UtilString.isEmpty(formFileId)) {
                isCreate = true;
                formFileId = UUIDGener.getUUID();
            }

            String groupValue = formFileId;
            if (copyFileOnly) {
                groupValue = config.getString("groupValue");
            }

            DCContext tmp = new DCContext(context.getSession(), DCProfileManager.getDCProfile(appId, "!form-ui-file-"), appId, groupValue, context.getFileValue(), context.getFileName(), context.getExtParam());
            tmp.setExtParams(context.getExtParams());
            tmp.getExtParams().put("boId", boId);
            return this.writeUIFile(tmp, appId, in, processInstId, taskInstId, boId, boItemName, boModel.getName(), formFileId, remark, isCreate, copyFileOnly);
        } else {
            return false;
        }
    }

    public void uploadSuccess(Map<String, Object> param) {
        DCContext context = (DCContext)param.get("DCContext");
        context.setDCMessage("ok", "");
        context.getDCMessage().addAttr("fileName", context.getFileName());
    }

    protected boolean writeUIFile(DCContext context, String appId, InputStream in, String processInstId, String taskInstId, String boId, String boItemName, String boName, String formFileId, String remark, boolean isCreate) throws Exception {
        return this.writeUIFile(context, appId, in, processInstId, taskInstId, boId, boItemName, boName, formFileId, remark, isCreate, false);
    }

    protected boolean writeUIFile(DCContext context, String appId, InputStream in, String processInstId, String taskInstId, String boId, String boItemName, String boName, String formFileId, String remark, boolean isCreate, boolean copyFileOnly) throws Exception {
        context.setEncrypt(FormFileUtil.getInstance().isEncrypt(boItemName, boName));
        DCStoreUtil.write(context, in);
        if (copyFileOnly) {
            return true;
        } else {
            FormFileDao dao = new FormFileDao();
            FormFileModel model = new FormFileModel();
            model.setId(formFileId);
            model.setAppId(appId);
            model.setBoId(boId);
            model.setBoName(boName);
            if (context.getSession() != null) {
                model.setCreateUser(context.getSession().getUID());
            }

            model.setCreateDate(new Timestamp((new Date()).getTime()));
            model.setProcessInstId(processInstId);
            model.setBoItemName(boItemName);
            model.setTaskInstId(taskInstId);
            model.setFileName(context.getFileName());
            String flstr = context.getFileLength();
            if (!UtilString.isEmpty(flstr)) {
                model.setFileSize(Long.parseLong(flstr));
            }

            model.setRemark(remark);
            int nowMaxOrderIndex = dao.getMaxOrderIndex(boId, boItemName);
            int orderIndex = nowMaxOrderIndex + 1;
            model.setOrderIndex(orderIndex);
            if (isCreate) {
                if (HighSecurity.isON() && HighSecurity.isSecurityLevel()) {
                    ProcessInstance processInst = ProcessRuntimeDaoFactory.createProcessInstance().getInstance(processInstId);
                    if (processInst != null) {
                        ProcessDefinition processDefinition = (ProcessDefinition)ProcessDefCache.getInstance().getModel(processInst.getProcessDefId());
                        if (processDefinition.isSecurityLayer()) {
                            String filename = context.getFileName();
                            if (filename.contains("普通")) {
                                model.setSecurityLevel(0);
                            } else if (filename.contains("秘密")) {
                                model.setSecurityLevel(1);
                            } else if (filename.contains("机密")) {
                                model.setSecurityLevel(2);
                            }
                        }
                    }
                }

                dao.insert(model);
            } else {
                dao.updateCreateDate(formFileId, model.getCreateDate());
                dao.update(formFileId, remark);
            }

            return true;
        }
    }

    public InputStream downloadContent(Map<String, Object> param) throws Exception {
        SDK.getLogAPI().consoleInfo("获取是否进入sdk的下载文件操作");
        DCContext context = (DCContext)param.get("DCContext");
        String formFileId = context.getGroupValue();
        FormFile formFileModel = (FormFile)(new FormFileDao()).queryById(formFileId);
        String appId=formFileModel.getAppId();
        String boName=formFileModel.getBoName();
        String boItemName=formFileModel.getBoItemName();
        String ext1=formFileModel.getExt1();//挂载的文件路径
        SDK.getLogAPI().consoleInfo("获取是否进入sdk的下载文件地址的表单id===="+formFileModel.getBoId());
        if("com.awspaas.user.apps.tcmp,com.awspaas.user.apps.tcmpinherent".indexOf(appId)>=0&&("BO_EU_TCMP_PROCESS,BO_EU_TCMP_PROCESS_IN".indexOf(boName)>=0)&&"DOWNLOAD_FILE".equals(boItemName)){
            SDK.getLogAPI().consoleInfo("获取是否进入sdk的下载文件地址===="+ext1);
            String portalUrl = SDK.getPortalAPI().getPortalUrl();
            HttpURLConnection conn = FileHelper.downLoadFromUrl( portalUrl+ext1);
            if (conn != null) {
              return conn.getInputStream();
            }
        }
        boolean isEncrypt = FormFileUtil.getInstance().isEncrypt(formFileModel.getBoItemName(), formFileModel.getBoName());
        context.setEncrypt(isEncrypt);
        InputStream in = DCStoreUtil.read(context);
        this.auditLog(context, formFileModel, "download");

        return in;
    }

    private void auditLog(DCContext context, FormFile formFileModel, String op) {
        FormEngineHelper.getInstance().operateAuditLog(context, formFileModel, op);
    }
}
